package represent.type;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import utils.Lib;

public class DateType implements Type {

	private Date val;
	public static DateFormat format = 
		new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public Object asJavaVal() {
		return toString();
	}

	public boolean equals(Object o) {
		DateType dv = null;
		if(o instanceof StringType)
			dv = new DateType( (String)(((StringType)o)).asJavaVal() );
		else if(o instanceof DateType)
			dv = (DateType) o;
		else
			throw new Error("Cannot convert " + o 
					+ " to type Datetime.");
		return val != null && val.equals(dv.val);
	}

	public DateType(String d) {
		try {
			val = format.parse(d);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	public int hashCode() {
		return val.hashCode();
	}

	public static boolean canParse(String s) {
		try {
			format.parse(s);
		} catch(ParseException e) {
			return false;
		}
		return true;
	}

	public String toString() {
		return format.format(val);
	}

	public Type divide(Type c) {
		throw new Error("Undefined operation.");
	}

	public String getType() {
		return "datetime";
	}

	public Type minus(Type c) {
		Lib.assertNotReached();
//		throw new Error("Undefined operation.");
		return null;
	}

	public Type mod(Type c) {
		Lib.assertNotReached();
//		throw new Error("Undefined operation.");
		return null;
	}

	public Type mult(Type c) {
		Lib.assertNotReached();
//		throw new Error("Undefined operation.");
		return null;
	}

	public Type plus(Type constant) {
		throw new Error("Undefined operation.");
	}

	public int compareTo(Type c) {
		DateType dv = null;
		if(c instanceof StringType)
			dv = new DateType( (String)(((StringType)c).asJavaVal()) );
		else if(c instanceof DateType)
			dv = (DateType) c;
		else
			throw new Error("Cannot convert " + c.asJavaVal() 
					+ " to type Datetime.");
		return val.compareTo(dv.val);
	}

	public static int compare(byte[] a, byte[] b) {
		// TODO �Զ���ɷ������
		return 0;
	}

	public static DateType fromBytes(byte[] bytes) {
		// TODO �Զ���ɷ������
		return null;
	}
	
	public int TypeToInt() {
		return utils.Constant.DATE;
	}
	
	public static int length() {
		return 4;
	}
	
}
